package com.example.kx037;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

/**
 * 图片切换器
 */
public class MainActivity extends AppCompatActivity {


    private int[] arrayPicture = new int[]{R.drawable.aaa, R.drawable.img01, R.drawable.img02, R.drawable.img03, R.drawable.fs};
    ImageSwitcher is;
    private int index;
    private float touchDownX;
    private float touchUpX;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        is = findViewById(R.id.imageSwitcher);

        is.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                ImageView imageView = new ImageView(MainActivity.this);
                imageView.setImageResource(arrayPicture[index]);
                return imageView;
            }
        });


        is.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                System.out.println("触发触碰");
                //按下
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    touchDownX = motionEvent.getX();
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    touchUpX = motionEvent.getX();

                    if (touchUpX-touchDownX>100){ //从左向右滑动
                        System.out.println("向右滑动");
                        index = index==0 ? arrayPicture.length-1: index-1;
                        //设置动画资源文件,现在没资料
                        is.setInAnimation(AnimationUtils.makeInAnimation(MainActivity.this,true));
                        is.setOutAnimation(AnimationUtils.makeOutAnimation(MainActivity.this,true));
                    }else if (touchUpX-touchDownX <-100){ //从右向左滑
                        System.out.println("向左滑动");
                        index = index ==arrayPicture.length-1 ? 0 : index+1;
                        is.setInAnimation(AnimationUtils.makeInAnimation(MainActivity.this,true));
                        is.setOutAnimation(AnimationUtils.makeOutAnimation(MainActivity.this,true));
                    }
                }
                return true;
            }
        });


    }
}